<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="name" label-width="100" label="商户名称" required>
				<uni-easyinput placeholder="商户名称" v-model="formData.name" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="logo" label-width="100" label="商户LOGO">
				<image v-if="formData.logo" :src="formData.logo" style="width: 100px; height: 100px;"></image>
			</uni-forms-item>
			<uni-forms-item name="contact" label="联系人">
				<uni-easyinput placeholder="联系人" v-model="formData.contact" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="email" label="邮箱">
				<uni-easyinput placeholder="邮箱" v-model="formData.email" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="phone" label="联系电话" required>
				<uni-easyinput placeholder="联系电话" v-model="formData.phone" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="address" label="商户地址">
				<uni-easyinput placeholder="商户地址" v-model="formData.address" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="description" label="商户描述">
				<uni-easyinput placeholder="商户描述" v-model="formData.description" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="business_license_number" label="营业执照号码">
				<uni-easyinput placeholder="营业执照号码" v-model="formData.business_license_number" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="business_license" label="营业执照">
				<image v-if="formData.business_license" :src="formData.business_license"
					style="width: 100px; height: 100px;"></image>
			</uni-forms-item>
			<uni-forms-item name="owner_id" label-width="100" label="商户管理员">
				<uni-easyinput placeholder="管理员" v-model="formData.ownername[0]" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="audit_status" label="审核状态">
				<uni-data-checkbox v-model="formData.audit_status"
					:localdata="formOptions.audit_status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="reject_reason" label="拒绝原因">
				<uni-easyinput placeholder="拒绝原因" v-model="formData.reject_reason"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/intangible_merchant.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'intangible_merchant';
	const dbOperation = uniCloud.importObject('db-merchant-operation')

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"owner_id": "",
				"ownername": "",
				"name": "",
				"logo": "",
				"contact": "",
				"email": "",
				"address": "",
				"business_license": "",
				"business_license_number": "",
				"description": "",
				"phone": "",
				"audit_status": 0,
				"reject_reason": "无"
			}
			return {
				percent: 0, //图片上传进度条
				formData,
				formOptions: {
					"status_localdata": [{
							"text": "关闭",
							"value": 0
						},
						{
							"text": "营业中",
							"value": 1
						}
					],
					"audit_status_localdata": [{
							"text": "待审核",
							"value": 0
						},
						{
							"text": "已通过",
							"value": 1
						},
						{
							"text": "已拒绝",
							"value": 2
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
				this.auditor_id = uniCloud.getCurrentUserInfo().uid
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			chooseLogoImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					},
					success: async function(res) {
						// console.log(res)
						let temp = await uniCloud.getTempFileURL({
							fileList: res.tempFiles.map((item) => item.url)
						});
						// console.log(111111111111,temp)
						_self.formData.logo = temp.fileList[0].tempFileURL
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
					},
					fail: function(err) {
						console.log(err)
						uni.showToast({
							icon: 'none',
							title: '上传失败',
							duration: 1500
						})
					}
				})
			},
			chooseLicenseImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					},
					success: async function(res) {
						// console.log(res)
						let temp = await uniCloud.getTempFileURL({
							fileList: res.tempFiles.map((item) => item.url)
						});
						// console.log(111111111111,temp)
						_self.formData.business_license = temp.fileList[0].tempFileURL
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
					},
					fail: function(err) {
						console.log(err)
						uni.showToast({
							icon: 'none',
							title: '上传失败',
							duration: 1500
						})
					}
				})
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					// console.log(99999,res)
					res.owner_id = res.owner_id[0]
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单，进行审核，只有审核成功才可以
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				// console.log(1111111111,value.owner_id)
				// return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
				// 	if(res.success){
				// 		//添加商户的角色
				// 		db.collection("uni-id-users").doc(value.owner_id).update({
				// 			role: 
				// 		}).then(()=>{
				// 			uni.showToast({
				// 				title: '审核通过'
				// 			})
				// 			this.getOpenerEventChannel().emit('refreshData')
				// 			setTimeout(() => uni.navigateBack(), 500)
				// 		}).catch((err)=>{
				// 			uni.showModal({
				// 				content: err.message || '审核服务失败',
				// 				showCancel: false
				// 			})
				// 		})
				// 	}

				// }).catch((err) => {
				// 	uni.showModal({
				// 		content: err.message || '审核服务失败',
				// 		showCancel: false
				// 	})
				// })
				//调用云函数实现商户审核
				// uniCloud.callFunction({
				// 		name: 'dbcmd-merchant-audit',
				// 		data: {
				// 			owner_id: value.owner_id,
				// 			formData: value,
				// 			formDataId: this.formDataId
				// 		}
				// 	})
				// 	.then(res => {
				// 		console.log(res)
				// 		uni.showToast({
				// 			title: res.result.message
				// 		})
				// 	}).catch((err) => {
				// 		console.error(err)
				// 		uni.showModal({
				// 			content: err.message || '审核服务失败',
				// 			showCancel: false
				// 		})
				// 	})
				if(value.audit_status==1){
					//审核通过，才向区块链服务器发请求获取商户的区块链信息
					uni.request({
						url: ' http://localhost:8888/api/accounts/createUser',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						method: 'POST',
						dataType: 'json',
						data: {
							userId: value.owner_id
						},
						success: async (blockres) => {
							value.blockaddress = blockres.data.data.blockaddress
							value.privatekey = blockres.data.data.privatekey
							value.auditor_id = this.auditor_id
							value.audit_time = new Date().getTime()
							// 使用云对象更新merchant表的相关信息
							dbOperation.merchant_audit(value.owner_id, this.formDataId, value).then(res => {
								
								if(res.success){
									//云对象执行从成功后，创建一条全新商户余额数据
									db.collection('intangible_merchantbalance').add({
										merchant_id: this.formDataId,
										available_balance: 0,
										frozen_balance: 0,
										total_income: 0,
										total_withdraw: 0,
										account_settings: {
											alipay_accounts: []
										},
										min_withdraw_amount: 100,
										daily_withdraw_limit: 5000,
										monthly_withdraw_limit: 20000,
										risk_level: 0,
										account_status: 0,
										remark: ''
									}).then(()=>{
										uni.showToast({
											title: res.message
										})
										this.getOpenerEventChannel().emit('refreshData')
										setTimeout(() => uni.navigateBack(), 500)
									})
								}else{
									console.error(res.error)
									uni.showModal({
										content: err.message || '审核服务失败',
										showCancel: false
									})
								}
								
							}).catch((err) => {
								console.error(err)
								uni.showModal({
									content: err.message || '审核服务失败',
									showCancel: false
								})
							})
							
							
							
						},
						fail: err => {
							console.log(err)
							uni.showModal({
								content: err.message ||
									'新增商户失败-请求区块链服务器失败',
								showCancel: false
							})
						}
					})
				}else{
					value.auditor_id = this.auditor_id
					value.audit_time = new Date().getTime()
					// 使用云对象更新merchant表的相关信息
					dbOperation.merchant_audit(value.owner_id, this.formDataId, value).then(res => {
						console.log(res)
						uni.showToast({
							title: res.message
						})
						this.getOpenerEventChannel().emit('refreshData')
						setTimeout(() => uni.navigateBack(), 500)
					}).catch((err) => {
						console.error(err)
						uni.showModal({
							content: err.message || '审核服务失败',
							showCancel: false
						})
					})
				}
				
				
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			async getDetail(id) {
				uni.showLoading({
					mask: true
				})
				try {
					const users = db.collection("uni-id-users").field("_id,username").getTemp()
					const res = await db.collection(dbCollectionName, users).where("_id=='" + id + "'")
						.field(
							"name,logo,contact,email,address,business_license,business_license_number,description,phone,audit_status,reject_reason,owner_id._id as owner_id,owner_id.username as ownername"
						).get()
					// console.log(222222222222,res)
					const data = res.result.data[0]

					if (data) {
						this.formData = data
						console.log(this.formData)
						uni.hideLoading()
						return data
					}
				} catch (error) {
					uni.showModal({
						content: error.message || '请求服务失败',
						showCancel: false
					})
				}


			}

		}
	}
</script>